/*
 * logon_sessmgr.cpp
 *
 *  Created on: Dec 16, 2013
 *      Author: killerg
 */

#include "auth_deps.h"
#include "logonsess.h"
#include "auth_cfg.h"
#include "auth.h"
#include "auth_mgr.h"

#include "share/msg.h"

bool logon_session_t::send_msg(la::AMsg* &msg) {
    return g_auth.logonsess_mgr->send_msg(this, msg);
}

void logon_session_t::update() {
}
void logon_session_t::on_connect() {
    UTIL_LOG(I, "on connect \n");
}
void logon_session_t::on_disconnect() {
	UTIL_LOG(I, "on disconnect \n");
}

void handle_lrequest(logon_session_t* sess, la::LMsg* msg) {
    auto &request = msg->request();
    int64_t logonsessid = sess->_sessid;
    int64_t sessid = request.sessid();

    auto fun = g_auth.authmgr->get_fun(request.epid());
    if (NULL == fun) {
        CREATE_LA_AMSG(AResponse, response);
        response->set_sessid(sessid);
        response->set_playerid(-1);
        response->set_data("");
        response->set_account("");
        response->set_mc("");
        sess->send_msg(___msg);
        return;
    }

    ++g_auth.authmgr->authed_ps;
    fun(to_json(request.data()), [logonsessid, sessid](int64_t playerid, const std::string &account, const std::string &mc, const std::string &data){
    	auto sess = g_auth.logonsess_mgr->connmgr.map_id.get(logonsessid);
        if (NULL == sess)
            return;

        CREATE_LA_AMSG(AResponse, response);
        response->set_sessid(sessid);
        if (playerid >= 0)
            response->set_playerid(playerid);
        if (!data.empty())
            response->set_data(data);
        if (!account.empty())
            response->set_account(account);
        if (!mc.empty())
        	response->set_mc(mc);

        sess->send_msg(___msg);
    });
}

bool logonsess_mgr_t::init() {
    bool ret = base::init(
            g_auth.cfg->ListenLogonIp.c_str(),
            g_auth.cfg->ListenLogonPort,
            1,
            -1,
            -1,
            0x0fffffff,
            false
            );
    if (!ret) {
        UTIL_LOG(I, "listening for logon at %s:%d failed",
                g_cfg->ListenLogonIp.c_str(),
                g_cfg->ListenLogonPort);
        return false;
    }

    UTIL_LOG(I, "listening for logon at %s:%d",
            g_cfg->ListenLogonIp.c_str(),
            g_cfg->ListenLogonPort);

    ret = ret && base::reg(la::ID_LRequest, handle_lrequest);
    return ret;
}
